package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.pojo.RecommendUser;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.config.MoRenLieBiaoConfig;
import com.tanhua.server.config.MoRenLieBiaoBestConfig;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class TodayBestService {

    @Autowired
    private UserService userService;

    //问题：写死到配置文件，不方便修改与维护？ -- 由学生自己解决这个问题
    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;

    @DubboReference(version = "1.0.0")
    private RecommendUserApi recommendUserApi;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @Autowired
    MoRenLieBiaoBestConfig moRenLieBiaoBestConfig;

    @Autowired
    MoRenLieBiaoConfig moRenLieBiaoConfig;

    public TodayBest queryTodayBest() {
        //校验token是否有效，获取userId
        Long userId = UserThreadLocal.get();

        //通过调用dubbo服务查询得分最高的用户
        RecommendUser recommendUser = this.recommendUserApi.queryWithMaxScore(userId);
        if (ObjectUtil.isEmpty(recommendUser)) {
            //给出一个默认的推荐用户
            recommendUser = new RecommendUser();
            recommendUser.setUserId(Long.valueOf(this.moRenLieBiaoBestConfig.getUserid()));
            recommendUser.setToUserId(userId);
            //随机一个得分
            recommendUser.setScore(RandomUtil.randomDouble(90, 99));
        }

        //根据用户id查询用户的基本信息
        UserInfo userInfo = this.userInfoApi.queryByUserId(recommendUser.getUserId());
        TodayBest todayBest = BeanUtil.toBeanIgnoreError(userInfo, TodayBest.class);
        todayBest.setGender(userInfo.getSex().name().toLowerCase());
        todayBest.setId(userInfo.getUserId());
        todayBest.setFateValue(recommendUser.getScore().longValue());
        return todayBest;
    }

    /**
     * 查询推荐用户列表
     *
     * @param
     * @param queryParam
     * @return
     */
    public PageResult queryRecommendation(RecommendUserQueryParam queryParam) {
        //校验token是否有效，获取userId
        Long userId = UserThreadLocal.get();
        PageResult pageResult = new PageResult();
        pageResult.setPage(queryParam.getPage());
        pageResult.setPagesize(queryParam.getPagesize());
        //查询dubbo服务，查询推荐列表
        PageInfo<RecommendUser> pageInfo = this.recommendUserApi.queryPageInfo(userId, queryParam.getPage(), queryParam.getPagesize());
        List<RecommendUser> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            //TODO 新用户默认的推荐列表
            String usersIds = moRenLieBiaoConfig.getUsersid();
            String[] usersIdsList = usersIds.split(",");
            List<Object> userIdList = new ArrayList<>();
            for (String usersId : usersIdsList) {
                userIdList.add(usersId);
            }
            List<UserInfo> userInfoList = this.userInfoApi
                    .queryByRecommendUser(userIdList, queryParam.getAge(), queryParam.getCity());
            //目标：封装TodayBest列表
            List<TodayBest> todayBestList = new ArrayList<>();
            for (UserInfo userInfo : userInfoList) {
                TodayBest todayBest = BeanUtil.toBeanIgnoreError(userInfo, TodayBest.class);
                todayBest.setGender(userInfo.getSex().name().toLowerCase());
                todayBest.setId(userInfo.getUserId());
                //随机获取分数
                todayBest.setFateValue(Convert.toLong(RandomUtil.randomDouble(50, 90)));
                // 查找到该用户所对应的RecommendUser对象，目的是获取它的得分
                todayBestList.add(todayBest);
            }
            //对集合排序
            Collections.sort(todayBestList, (o1, o2) ->
                    Convert.toInt(o2.getFateValue() - o1.getFateValue()));
            pageResult.setItems(todayBestList);
            return pageResult;
        }
        //老用户推荐列表
        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoApi
                .queryByRecommendUser(userIdList, queryParam.getAge(), queryParam.getCity());
        if (CollUtil.isEmpty(userInfoList)) {
            return pageResult;
        }
        //目标：封装TodayBest列表
        List<TodayBest> todayBestList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = BeanUtil.toBeanIgnoreError(userInfo, TodayBest.class);
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setId(userInfo.getUserId());
            // 查找到该用户所对应的RecommendUser对象，目的是获取它的得分
            for (RecommendUser record : records) {
                if (ObjectUtil.equal(record.getUserId(), userInfo.getUserId())) {
                    todayBest.setFateValue(record.getScore().longValue());
                    break;
                }
            }
            todayBestList.add(todayBest);
        }
        Collections.sort(todayBestList, (o1, o2) -> Convert.toInt(o2.getFateValue() - o1.getFateValue()));

        //TODO 排除今日佳人的用户
        //排除今日佳人
        if (queryParam.getPage() == 1) {
            todayBestList.remove(0);
        }
        //对集合排序
        Collections.sort(todayBestList, (o1, o2) ->
                Convert.toInt(o2.getFateValue() - o1.getFateValue()));
        pageResult.setItems(todayBestList);
        return pageResult;
    }
}
